//---------------------------------------------------------------------------
// Process Class
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr
// Date : Jul. 7, 2006
//---------------------------------------------------------------------------
#include "CSync.h"
//---------------------------------------------------------------------------
CSync::CSync()
{
	up_pipefd[0] = -1;
	up_pipefd[1] = -1;
	down_pipefd[0] = -1;
	down_pipefd[1] = -1;

	if(initialize()<0) exit(-1);
}
//--------------------------------------------------------------------------
CSync::~CSync()
{
	if(up_pipefd[0]>0) close(up_pipefd[0]);
	if(up_pipefd[1]>0) close(up_pipefd[1]);

	if(down_pipefd[0]>0) close(down_pipefd[0]);
	if(down_pipefd[1]>0) close(down_pipefd[1]);
}
//--------------------------------------------------------------------------
int CSync::initialize()
{
	if(pipe(up_pipefd)<0||pipe(down_pipefd)<0) {
		cerr << "pipe error" << endl;
		return -1;
	}

	return 1;
}
//--------------------------------------------------------------------------
// on child
//--------------------------------------------------------------------------
int CSync::tell_parent(pid_t pid)
{
	if(write(up_pipefd[1], "c", 1)!=1) {
		cerr << "pipe write error" << endl;
		return -1;
	}

	return 1;
}
//--------------------------------------------------------------------------
// on child
//--------------------------------------------------------------------------
int CSync::wait_parent()
{
	char c;

	if(read(down_pipefd[0], &c, 1)!=1) {
		cerr << "pipe read error" << endl;
		return -1;
	}

	if(c!='p') {
		cerr << "pipe data error : wait_parent()" << endl;
		return -1;
	}

	return 1;
}
//--------------------------------------------------------------------------
// on parent 
//--------------------------------------------------------------------------
int CSync::tell_child(pid_t pid)
{
	if(write(down_pipefd[1], "p", 1)!=1) {
		cerr << "pipe write error" << endl;
		return -1;
	}
	return 1;
}
//--------------------------------------------------------------------------
// on parent 
//--------------------------------------------------------------------------
int CSync::wait_child()
{
	char c;

	if(read(up_pipefd[0], &c, 1)!=1) {
		cerr << "pipe read error" << endl;
		return -1;
	}

	if(c!='c') {
		cerr << "pipe data error : wait_child()" << endl;;
		return -1;
	}

	return 1;
}
//--------------------------------------------------------------------------
